package com.innovation.ic.cc.base.service.cc.impl;

import com.innovation.ic.cc.base.model.cc.MenuTree;
import com.innovation.ic.cc.base.pojo.variable.ServiceResult;
import com.innovation.ic.cc.base.service.cc.MenuTreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * MenuService的具体实现类
 */
@Service
@Transactional
public class MenuTreeServiceImpl  implements MenuTreeService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 先删除旧的，再添加新的MenuTree对象
     * @param menuTree
     * @return
     */
    @Override
    public ServiceResult<MenuTree> saveOrUpdateMenuTree(MenuTree menuTree) {
        ServiceResult<MenuTree> serviceResult = new ServiceResult<MenuTree>();

        // 删除
        Query query = Query.query(Criteria.where("userId").is(menuTree.getUserId()));
        mongoTemplate.remove(query, MenuTree.class);

        // 添加
        MenuTree result = mongoTemplate.insert(menuTree);

        serviceResult.setMessage(ServiceResult.INSERT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 根据userId，查找MenuTree对象
     * @param userId
     * @return
     */
    @Override
    public ServiceResult<MenuTree> findByUserId(String userId) {
        ServiceResult<MenuTree> serviceResult = new ServiceResult<MenuTree>();

        // 删除
        Query query = Query.query(Criteria.where("userId").is(userId));
        MenuTree menuTree = mongoTemplate.findOne(query, MenuTree.class);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(menuTree);
        return serviceResult;
    }
}
